import {Component, Inject, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {AccountService} from '../_services/account.service';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {AlertService} from '../_services/alert.service';
import {User} from '../_models/user';

@Component({templateUrl: 'dialog-addUser.component.html'})
export class DialogAddUserComponent implements OnInit{
  form: FormGroup;
  submitted = false;
  constructor(
    private formBuilder: FormBuilder,
    private accountService: AccountService,
    public dialogRef: MatDialogRef<DialogAddUserComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private alertService: AlertService
  ) {}

  onSubmit(): void {
    this.submitted = true;
    this.alertService.clear();
    if (this.form.invalid ) {
      return;
    }
    if (this.data === null){
      this.accountService.add(this.form.value as User)
        .subscribe({
          next: (resp) => {
            if (resp.code === '200'){
              alert('添加成功');
            }
          },
          error: error => {
            this.alertService.error(error);
          }
        });
    }else {
      this.accountService.edit(this.form.value as User)
        .subscribe({
          next: (resp) => {
            if (resp.code === '200'){
              alert('修改成功');
            }
          },
          error: error => {
            this.alertService.error(error);
          }
        });
    }
    this.dialogRef.close();
  }

  get f(): any {
    return this.form.controls;
  }

  ngOnInit(): void {
    if (this.data !== null){
      this.form = this.formBuilder.group({
        id: [this.data.id, Validators.required],
        name: [this.data.name, Validators.required],
        password: [this.data.password, Validators.required],
        gender: [this.data.gender, Validators.required],
        address: [this.data.address, Validators.required],
        phone: [this.data.phone, Validators.required],
        email: [this.data.email, Validators.required],
        role: [this.data.role, Validators.required]
      });
    }else {
      this.form = this.formBuilder.group({
        id: ['', null],
        name: ['', Validators.required],
        password: ['', Validators.required],
        gender: ['', Validators.required],
        address: ['', Validators.required],
        phone: ['', Validators.required],
        email: ['', Validators.required],
        role: ['', Validators.required]
      });
    }
  }
}
